package com.yunding.house.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.yunding.house.pojo.Phonecode;
import com.yunding.house.service.IWxuserService;
import com.yunding.house.service.PhonecodeService;
import com.yunding.house.service.UserService;
import com.yunding.house.utils.R;
import com.yunding.house.utils.SendCode;
import com.yunding.house.utils.SmsUtils;
import com.yunding.house.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class PhonecodeController {

    @Autowired
    private UserService userService;
    @Autowired
    private IWxuserService iWxuserService;
    @Autowired
    private PhonecodeService phonecodeService;

    @RequestMapping("/sendcode")
    public R sendcode(@RequestParam(value = "phone",required = false) String phone) throws ClientException {

        boolean boo =  SendCode.isPhoneNumber(phone.trim());
        if(boo) {
            Phonecode phonecode = phonecodeService.IsSendCodephoneInfo(phone.trim());

            int Length = 5;
            String codes = SmsUtils.vcode(Length);
            System.out.println("codecodecode=" + codes);
            if (phonecode == null) {
                // 第一次获取验证码
                // 存入数据库
                SendSmsResponse sendSms = SmsUtils.sendSms(phone.trim(), codes);
                phonecode.setPhone(phone);
                phonecode.setCode(codes);
                phonecode.setUpdattime(new Date());
                phonecodeService.save(phonecode);
                return new R(true, StatusCode.OK, "保存成功", phonecode);
            } else {
                // 更新数据库验证码
                SendSmsResponse sendSms = SmsUtils.sendSms(phone, codes);
                phonecode.setCode(codes);
                phonecode.setUpdattime(new Date());

                phonecodeService.update(phonecode);
                return new R(true, StatusCode.OK, "保存成功", phonecode);
            }
        }else {
            return new R(false, StatusCode.PHONE, "失败");
        }
    }
}
